package br.gov.ba.mam.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import br.gov.ba.mam.beans.Categoria;
import br.gov.ba.mam.beans.Mensagem;
import br.gov.ba.mam.gerente.GerenteAplicacao;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

class TelaCadCategoria extends JPopupMenu {

	private static final long serialVersionUID = 1L;
	private CellConstraints cc = new CellConstraints();
	
	private Categoria categoria;
	
	private ChangeListener changeListener;

	private JTextField txtNome;
	private JButton btRemover;
	
	public TelaCadCategoria(ChangeListener change) {
		super();
		changeListener = change;
		add(getPainelPopUp());
	}
	
	private JComponent getPainelPopUp() {
		
		PanelBuilder form = new PanelBuilder(new FormLayout("10dlu,45dlu,5dlu,60dlu,10dlu","10dlu,15dlu,10dlu,15dlu,10dlu,16dlu,10dlu"));
		
		form.addLabel("Nome :",cc.xy(2, 4));
		txtNome = new JTextField();
		form.add(txtNome,cc.xy(4, 4));
		
		JButton btApp = new JButton();
		btApp.setText("Salvar");
		btApp.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				Categoria cat = categoria;
				if(categoriaIsValida()){
					cat = new Categoria(txtNome.getText());
					GerenteAplicacao.getInstancia().salvarCategoria(cat);
					TelaAviso.telaSucesso(TelaCadCategoria.this, Mensagem.SUCESSO_CATEGORIA.toString());
					TelaCadCategoria.this.setVisible(false);
					changeListener.stateChanged(new ChangeEvent(cat));
				} else {
					TelaAviso.telaErro(TelaCadCategoria.this, Mensagem.ERRO_NOME_CATEGORIA.toString());
				}
			}
		});
		
		btRemover = new JButton("Remover");
		btRemover.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				if(!(categoria.getCodigo() == 0)){
					GerenteAplicacao.getInstancia().removerCategoria(categoria.getCodigo());
				}
				TelaCadCategoria.this.setVisible(false);
				changeListener.stateChanged(new ChangeEvent(categoria));
			}
		});
		
		form.add(ButtonBarFactory.buildCenteredBar(btApp, btRemover),cc.xyw(1, 6, 5));
		
		
		return form.getPanel();
	}

	protected boolean categoriaIsValida() {
		if(!txtNome.getText().isEmpty()){
			return true;
		}
		return false;
	}

	public void setCategoria(Categoria selectedItem) {
		this.categoria = selectedItem;
		if(categoria.getCodigo() == 0){
			btRemover.setEnabled(false);
			categoria = new Categoria();
		} else {
			btRemover.setEnabled(true);
		}
		txtNome.setText(categoria.getNome());
		
	}

}
